/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/**
 *
 * @author Weslei
 */
public class SMSender{
    
  private MessageConnection smsconn = null;

  private Vector txtmessages = new Vector();
  
  private ThreadEnvio envio;
  
  public SMSender() throws IOException {
        // Open the message connection.
        smsconn = (MessageConnection) (MessageConnection)Connector.open("sms://5000");
        envio = new ThreadEnvio();
        envio.start();
  }
  
  public void fechar(){
        try {
            smsconn.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        envio.interrupt();
        envio = null;
  }

  public void send(String message, String phoneNumber) throws Exception{   
    // Create the message.
    TextMessage txtmessage = (TextMessage ) smsconn.newMessage(MessageConnection.TEXT_MESSAGE);
        
    txtmessage.setAddress("sms://"+phoneNumber);
    txtmessage.setPayloadText(message);

    synchronized(txtmessages){
        txtmessages.addElement(txtmessage);
        txtmessages.notifyAll();
    }
  }
  
  private class ThreadEnvio extends Thread{        
        public void run() {
            while(true){
                //System.out.println("passando ThreadEnvio");
                synchronized(txtmessages){
                    if(txtmessages.size()>0){
                        for (int i = 0; i < txtmessages.size(); i++) {
                            TextMessage tx = (TextMessage) txtmessages.elementAt(i);
                            //System.out.println("enviando: "+tx.getPayloadText());
                            try {
                                smsconn.send(tx);
                            } catch (IOException ex) {
                            } 
                        }   
                        txtmessages.removeAllElements();
                    }
                    try {
                        txtmessages.wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
  }
  
}
